<template>
  <div>
    <el-main>
      <el-button type="danger" round @click="delByIds">删除已选中</el-button>
      <el-button type="success" round @click="dialogFormVisible=true">添加新游戏</el-button>
      &emsp;
      <el-select v-model="searchClassIdToName" filterable placeholder="请选择游戏类型进行筛选查询">
        <el-option
          v-for="item in allGameClassesForSearch"
          :key="item.id"
          :label="item.classesName"
          :value="item.id">
        </el-option>
      </el-select>
      <el-table :data="tableData.records"  @selection-change="addIds">
        <el-table-column type="selection">
        </el-table-column>
        <el-table-column label="游戏类型" width="120" :formatter="getGameClasses">
        </el-table-column>
        <el-table-column prop="simpleName" label="游戏名" width="120">
        </el-table-column>
        <el-table-column prop="fullName" label="游戏全名" width="120">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="danger" icon="el-icon-delete" circle @click.native.prevent="delById(scope.row)"></el-button>            
            <!-- 修改 -->
            <el-button type="primary" icon="el-icon-edit" circle @click.native.prevent="updateById(scope.row)"></el-button>
            <el-dialog title="游戏信息" :visible.sync="dialogFormVisible" close-on-press-escape :before-close="clearUpdateData">
              <el-form :model="game">
              <el-form-item label="游戏简称" :label-width="formLabelWidth">
                <el-input v-model="game.simpleName" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="游戏全称" :label-width="formLabelWidth">
                <el-input v-model="game.fullName" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="游戏类型" :label-width="formLabelWidth">  
                <el-select v-model="classesIdToName" filterable placeholder="请选择">
                  <el-option
                    v-for="item in allGameClasses"
                    :key="item.id"
                    :label="item.classesName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
              <el-button @click="clearUpdateData">取 消</el-button>
              <el-button type="primary" @click="updateManagerByIdArAddNew">确 定</el-button>
              </div>
            </el-dialog>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <common-footer :pageData="tableData" ref="footData"></common-footer>
  </div>
</template>

<script>
import CommonFooter from '@/components/CommonFooter.vue'
import axios from 'axios'
    export default {
        name:'GamesPage',
        components:{CommonFooter},
        data(){
          return{
            tableData:{},
            allGameClasses:[],
            allGameClassesForSearch:[],
            ids:[],
            formLabelWidth: '120px',
            dialogFormVisible:false,
            game:{
              id:'',
              simpleName:'',
              fullName:'',
              classesId:'',
            },
            searchClassId:'',
          }
        },
        props:["page","pageSize"],
        mounted() {
          this.$refs.footData.$on('pageSize',this.getPageSize);//接收子组件分页栏的每页显示条目数
          this.$refs.footData.$on('currentPage',this.getCurrentPage);//接收子组件分页栏的数据
          axios.get(`/games/getPage?page=${this.page}&pageSize=${this.pageSize}`).then(
            response=>{
                this.tableData=response.data.data;
              },
            error=>{
              console.log("请求失败。原因是",error.message);
            }
          );
          axios.get('/game-category/getAll').then(
            response=>{
              this.allGameClasses=response.data.data;
              this.allGameClassesForSearch=[].concat(this.allGameClasses);
              this.allGameClassesForSearch.unshift({
                id:'',
                classesName:'-->不进行游戏类别筛选',
              });
            }
          )
        },
        methods:{
          getGameClasses(row){//用查到的游戏类别名在和游戏一一对应
            var gn="";
            this.allGameClasses.forEach((gameClasses)=>{
                if(row.classesId===gameClasses.id){
                    gn=gameClasses.classesName;
                    return
                }
            })
            return gn;
          },
          getPageSize(pagesize){//改变每页数据量，触发监控属性让其法请求更新页面
            this.tableData.size=pagesize;
          },
          getCurrentPage(currentpage){//改变当前页，触发监控属性让其法请求更新页面
            this.tableData.current=currentpage;
          },
          updataPageData(){//用于更新页面内容，模糊查询，翻页等等
            axios.get(`/games/getPage?page=${this.tableData.current}&pageSize=${this.tableData.size}&classesId=${this.searchClassId}`).then(
            response=>{
              this.tableData=response.data.data;
              this.game={
                id:'',
                simpleName:'',
                fullName:'',
                classesId:'',
              };
            },
            error=>{
              console.log("请求失败。原因是",error.message);
            }
            );
          },
          delById:async function(roo){//删除单个游戏
            if(confirm("确定删除游戏“"+roo.fullName+"”吗")){
              await new Promise((resolve,reject)=>{
                axios.get(`/games/delById?id=${roo.id}`).then(
                  response=>{
                      resolve();
                      alert(response.data.data)
                  },
                  error=>{
                      console.log("请求失败。原因是",error.message);
                      reject();
                  }
                );
              })
              await new Promise((resolve)=>{
                this.updataPageData().then(resolve());
              })
              this.$forceUpdate();//迫使Vue实例重新渲染
            }
          },
          delByIds:async function(){//删除多个游戏
            if(confirm("确定删除所有已选中的游戏吗？")&&this.ids.length!==0){
              await new Promise((resolve,reject)=>{
                let params=new URLSearchParams();
                params.append('ids',this.ids);
                axios(
                  {
                    method:'get',
                    url:'/games/delByIds',
                    params
                  }
                ).then(
                  response=>{
                      alert(response.data.data);
                      resolve();
                  },
                  error=>{
                      console.log("请求失败。原因是",error.message);
                      reject();
                  }
                );
                
              })
              this.tableData.current=1;
              await new Promise((resolve)=>{
                this.updataPageData().then(resolve());
              })
              this.$forceUpdate();//迫使Vue实例重新渲染
            }
          },
          addIds(val){//多选框发生变化后更新选择数组，用于之后连续delByIds用
            var momentIds=[];
            val.forEach((data) => {
              momentIds.push(data.id)
            });
            this.ids=momentIds;
          },
          updateById(val){//进入修改页面
            this.dialogFormVisible = true;//开启信息页面
            this.game.id=val.id;
            this.game.simpleName=val.simpleName;
            this.game.fullName=val.fullName;
            this.game.classesId=val.classesId;
          },
          updateManagerByIdArAddNew(){//发请求进行修改或者新添
            this.dialogFormVisible = false;
            // console.log("数据时",this.game);
            if(this.game.id===''){//没有id则为新增
            axios(
              {
                method:'post',
                url:'/games/addNew',
                data:this.game,
              }
            ).then(
              response=>{
                  response;
                  this.updataPageData();
                  alert('添加新游戏成功');
              }
            )
            }else{//有id则为修改‘
              axios(
                {
                  method:'post',
                  url:'/games/updateById',
                  data:this.game,
                }
              ).then(
                response=>{
                  response;
                  this.updataPageData();
                  alert('修改游戏成功');
                }
              );
            }       
          },
          clearUpdateData(){//关闭对话框时清空表单数据
            this.dialogFormVisible = false;
            this.game={
              id:'',
              simpleName:'',
              fullName:'',
              classesId:'',
            };
          }
        },
        watch:{
        'tableData.size':{
            handler(newValue,oldValue){
              if(oldValue!==undefined){
                this.updataPageData();
              } 
            }
        },
        'tableData.current':{
            handler(newValue,oldValue){
              if(oldValue!==undefined){
                this.updataPageData();
              }
            }
        },
        searchClassId(){
          if(this.tableData.current===1){
              this.updataPageData();
          }else{
              this.tableData.current=1;
          }
        }
      },
      computed:{
        classesIdToName:{//使用计算属性+v-model，来解决游戏类名与游戏类id对应的问题
          get(){
            var gn="";
            this.allGameClasses.forEach((gameClasses)=>{
                if(this.game.classesId===gameClasses.id){
                    gn=gameClasses.classesName;
                    return
                }
            })
            return gn;
          },
          set(value){
            this.game.classesId=value;
          }
        },
        searchClassIdToName:{//计算属性，用于游戏类别查询
          get(){
            var gn="";
            this.allGameClassesForSearch.forEach((gameClasses)=>{
                if(this.searchClassId===gameClasses.id){
                    gn=gameClasses.classesName;
                    return
                }
            })
            return gn;
          },
          set(val){
            this.searchClassId=val;
          }
        }
      },
    }
</script>

<style>

</style>